<template>
    <div>
        <!-- 查询条件开始 -->
        <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
            <el-form-item label="菜单名称" prop="menuName">
                <el-input
                        v-model="queryParams.menuName"
                        placeholder="请输入菜单名称"
                        clearable
                        size="small"
                        style="width:240px"
                />
            </el-form-item>
            <el-form-item label="状态" prop="status">
                <el-select
                        v-model="queryParams.status"
                        placeholder="请选择状态"
                        clearable
                        size="small"
                        style="width:200px"
                >
                    <el-option
                            v-for="dict in statusOptions"
                            :key="dict.dictValue"
                            :label="dict.dictLabel"
                            :value="dict.dictValue"
                    />
                </el-select>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini"@click="getMenuList" >搜索</el-button>
                <el-button type="danger" icon="el-icon-plus" size="mini" @click="handleAdd">添加</el-button>
            </el-form-item>
        </el-form>
        <!-- 查询条件结束 -->
        <!-- 数据表格开始 -->
        <el-table
                border
                :data="menuTableList"
                row-key="menuId"

        >
            <el-table-column label="菜单名称" align="left" prop="menuName" />
            <el-table-column label="菜单类型" align="center" prop="menuType">
                <template slot-scope="scope">
                    <el-tag
                            :type="scope.row.menuType==='M'?'primary':scope.row.menuType==='C'?'danger':'success'"
                    >
                        {{ scope.row.menuType==='M'?'目录':scope.row.menuType==='C'?'菜单':'权限' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="组件路径" align="center" prop="path" />
            <el-table-column label="权限标识" align="center" prop="percode" />
            <el-table-column label="状态" align="center" prop="status"  :formatter="statusFormat" />
            <el-table-column label="创建时间" align="center" prop="createTime" />
            <el-table-column label="备注" align="center" prop="remark" />
            <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                    <el-button type="text" icon="el-icon-edit" size="mini" @click="handleUpdate(scope.row)" >修改</el-button>
                    <el-button type="text" icon="el-icon-delete" size="mini"@click="delPro(scope.row)" >删除</el-button>
                </template>
            </el-table-column>

        </el-table>
        <!-- 数据表格结束 -->
        <!-- 添加和修改的弹出层开始 -->
        <el-dialog
                :title="title"
                :visible.sync="open"
                width="600px"
                center
                append-to-body
                :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        >
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="上级菜单" prop="parentName">
                            <treeselect
                                    v-model="form.parentId"
                                    :options="menuOptions"
                                    :show-count="true"
                                    :normalizer="normalizer"
                                    placeholder="请选择上级菜单"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="菜单类型" prop="menuType">
                            <el-radio-group v-model="form.menuType">
                                <el-radio label="M">目录</el-radio>
                                <el-radio label="C">菜单</el-radio>
                                <el-radio label="F">按钮</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="菜单名称" prop="menuName">
                            <el-input v-model="form.menuName" placeholder="请输入菜单名称" clearable size="small" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="路由地址" prop="path">
                            <el-input v-model="form.path" placeholder="请输入路由地址" clearable size="small" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item v-if="form.menuType==='F'" label="权限标识" prop="percode">
                            <el-input v-model="form.percode" placeholder="请输入权限标识" clearable size="small" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="状态" prop="status">
                            <el-radio-group v-model="form.status">
                                <el-radio
                                        v-for="dict in statusOptions"
                                        :key="dict.dictValue"
                                        :label="dict.dictValue"
                                        :value="dict.dictValue"
                                >{{ dict.dictLabel }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="form.remark" type="textarea" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </span>
        </el-dialog>
        <!-- 添加和修改的弹出层结束 -->

    </div>
</template>

<script>
    import qs from "qs";
    import Treeselect from "@riophae/vue-treeselect";
    import "@riophae/vue-treeselect/dist/vue-treeselect.css";
    export default {
        name: "Menu",
        components: { Treeselect },
        data() {
            return {
                // 遮罩层
                loading: false,
                // 菜单表的数据
                menuTableList: [],
                // 菜单树的数据
                menuOptions: [],
                // 弹出层的title
                title: '',
                // 是否打开弹出层
                open: false,
                // 状态数据字典
                statusOptions: [],
                // 查询参数
                total: 0,
                pageSize: 5,
                currentPage:1,
                queryParams: {},

                // 表单数据
                form: {},
                // 表单校验
                rules: {
                    menuName: [
                        { required: true, message: '菜单名称不能为空', tirgger: 'blur' }
                    ]
                }
            }
        },
        created() {
            this.getTreeselect();
            this.getMenuList();
            this.initStatus();
        },
        methods: {
            handleUpdate(row){
                this.getTreeselect();
                this.open=true;
                this.form=JSON.parse(JSON.stringify(row));
            },
            handleAdd(){
                this.getTreeselect();
                this.open=true;
                this.form={};
            },

            handleSubmit(){
                this.$refs.form.validate((valid)=>{
                    if (valid){
                        this.$axios.post("/system/api/menu/saveAndUpdate",qs.stringify(this.form)).then(result=>{
                            if (result.data.data){
                                this.$message.success("添加成功")
                                this.open=false
                                this.form={}
                                this.getMenuList()
                                this.getTreeselect();
                            }else {
                                this.$message.error("添加失败");
                            }
                        })
                    }else {
                        console.log('error submit!!')
                        return false
                    }
                })
            },


            // 取消
            cancel() {
                this.open = false
                this.title = ''
            },
            // 删除操作
            delPro(obj){
                this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$axios.delete(`/system/api/meun/delById/${obj}`).then(result=>{
                        if (result.data.data){
                            // alert(result.data.t); // 测试弹出获取的数据信息,返回true/false
                            this.initDept();
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                        }else {
                            this.$message({
                                type: 'error',
                                message: '删除失败!'
                            });
                        }
                    })
                }).catch(() => {
                    this.$message.error({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },

            // 自定义键名
            normalizer(node) {
                if (node.children && !node.children.length) {
                    delete node.children
                }
                return {
                    id: node.menuId,
                    label: node.menuName,
                    children: node.children
                }
            },
            // // 查询菜单下拉树的数据
            getTreeselect() {
                this.$axios.get("/system/api/menu/list").then(res=>{
                    this.menuOptions=res.data.data;
                    // console.log(this.menuOptions)
                    /** *
                     * 构造树的数据结构
                     * @param data 要构造的数据源
                     * @param id 字段ID  默认为id
                     * @param parentId 父节点字端  默认为parentId
                     * @param children 子节点的字段 默认为children
                     * @param rootId 根节点的ID  默认为0
                     */
                    function handleTree(data, id, parentId, children, rootId) {
                        id = id || 'menuId'
                        parentId = parentId || 'parentId'
                        children = children || 'children'
                        rootId = rootId || 0
                        // 对源数据进行深度克隆
                        const cloneData = JSON.parse(JSON.stringify(data))
                        // 循环所有的项目
                        const treeData = cloneData.filter(father => {
                            const branchArr = cloneData.filter(child => {
                                return father[id] === child[parentId]
                            })
                            branchArr.length > 0 ? father.children = branchArr : ''
                            // 返回上一层
                            return father[parentId] === rootId
                        })
                        return treeData !== '' ? treeData : data
                    }
                    // console.log(handleTree(res.data.data,'menuId'))
                    this.menuTableList=handleTree(res.data.data,'menuId')



                })
            },
            //查询全部数据
            getMenuList(){
                this.loading = true
                this.$axios.post("system/api/menu/searchMenu/"+this.currentPage+"/"+this.pageSize+"/",this.queryParams).then(result=>{
                    this.menuTableList=result.data.data.records
                    this.total=result.data.data.total
                })
            },
            //状态解析
            statusFormat(row) {
                let v = row.status;
                return this.formatDict(this.statusOptions, v);
            },

            //初始化状态
            initStatus() {
                this.$axios.get("/system/api/dict/data/findByType/sys_normal_disable").then(result => {
                    this.statusOptions = result.data.data;
                })
            },

        }
    }
</script>

<style scoped>

</style>
